<?php
/**
 * @desc 微信.商户支付
 * @document https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
 * @author Vincent
 */

namespace young\payment;

use young\Common;

class WxMchPay extends WxConfig
{
    public function run($data)
    {
        $this->setConfig($data['config']);
        return $this->handle($data['desc'], $data['order_sn'], $data['amount'], $data['openid']);
    }

    public function handle($desc, $orderSn, $amount, $openid)
    {
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
        $common = [];
        $common['mch_appid'] = $this->appid;
        $common['mchid'] = $this->mch_id;
        $common['nonce_str'] = Common::rand_string(32);
        $common['partner_trade_no'] = $orderSn;
        $common['openid'] = $openid;
        $common['check_name'] = 'NO_CHECK';
        $common['amount'] = $this->formatAmount($amount);
        $common['desc'] = $desc;
        $common['spbill_create_ip'] = $_SERVER['REMOTE_ADDR'];
        $common['sign'] = $this->sign($common);
        $xml = Common::arrayToXml($common);
        $result = $this->request_post($url, $xml);
        $result = Common::xmlToArray($result);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            return true;
        } else {
            throw new \Exception('[code:' . $result['return_code'] . '][msg:' . $result['return_msg'] . '][err_code_des:' . $result['err_code_des'] . ']');
        }
    }
}